using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel.Channels;
using System.Xml;

namespace Telecom.SDP.Common.ServiceModel
{
    public class HttpPostMessage : Message
    {
        private string _payload = string.Empty;

        public string Payload
        {
            get { return _payload; }
            set { _payload = value; }
        }

        public HttpPostMessage(string payload)
        {
            _payload = payload;
        }

        public HttpPostMessage() { }

        public override MessageHeaders Headers
        {
            get
            {
                return new MessageHeaders(MessageVersion.None);
            }
        }

        protected override void OnWriteBodyContents(System.Xml.XmlDictionaryWriter writer)
        {
            writer.WriteStartElement("Message", "http://Telecom.SDP.BizTalk.Schemas.Message/2008/07/31");
            writer.WriteRaw(Payload);
            writer.WriteEndElement();
        }

        protected override void OnClose()
        {
            base.OnClose();
        }

        protected override void OnWriteStartHeaders(System.Xml.XmlDictionaryWriter writer) { }

        protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize)
        {
            return base.OnCreateBufferedCopy(maxBufferSize);
        }

        protected override void OnWriteStartBody(System.Xml.XmlDictionaryWriter writer) { }

        protected override void OnBodyToString(System.Xml.XmlDictionaryWriter writer)
        {
            writer.WriteRaw(Payload);
        }

        protected override void OnWriteMessage(System.Xml.XmlDictionaryWriter writer)
        {
            writer.WriteRaw(Payload);
        }

        public override string ToString()
        {
            return base.ToString();
        }

        public override MessageProperties Properties
        {
            get { return new MessageProperties(); }
        }

        public override MessageVersion Version
        {
            get { return MessageVersion.None; }
        }

        /// <summary>
        /// This is used to convert the received message into a Message for transmission
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        internal static HttpPostMessage CreateMessage(Message message)
        {
            XmlDictionaryReader reader = message.GetReaderAtBodyContents();

            reader.MoveToContent();
            string s = reader.ReadOuterXml();
            reader.Close();

            message.Close();

            return new HttpPostMessage(s);

        }
    }
}
